package cn.icatw.leetcode.editor.cn.juc;

import java.util.concurrent.Semaphore;

/**
 * @author 王顺 762188827@qq.com
 * @apiNote 信号量模拟，十个请求，三个并发
 * @since 2024/8/14
 */
public class SemaphoreExample {
    public static void main(String[] args) {
        int n = 10;
        int semaphoreCount = 3;
        Semaphore semaphore = new Semaphore(semaphoreCount);
        Thread[] threads = new Thread[n];
        for (int i = 0; i < 10; i++) {
            threads[i] = new Thread(() -> {
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + "开始执行");
                    Thread.sleep(5000);
                    System.out.println(Thread.currentThread().getName() + "执行完毕");
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        for (Thread thread : threads) {
            thread.start();
        }
    }
}
